import { PageContainer } from '@ant-design/pro-layout';
import ProCard from '@ant-design/pro-card';
import {
  ProFormTextArea,
  ProFormText,
  ProFormSelect,
  ProFormUploadDragger,
  StepsForm,
} from '@ant-design/pro-form';
import { useModel } from '@@/plugin-model/useModel';
import React, { useRef } from 'react';
import { message } from 'antd';
import { postItem } from '@/services/aqchain-antd/item';
import { history } from 'umi';
import type { FormInstance } from 'antd';

declare type FileStorageParams = {
  fileHash:string;
  creator:string;
}

const AddItem: React.FC = () => {
  const { initialState } = useModel('@@initialState');
  const {
    provider,
    contracts: { testContract,fileStorageContract },
  } = initialState!;

  const formRef = useRef<FormInstance<FileStorageParams>>();

  // 文件上传
  const onFileUpload = async (values:API.FormDataModelsItemPost & {files:any}) => {
    try {
      const signer = provider.getSigner();
      values.address = await signer.getAddress();
      values.signature = await signer.signMessage(
        'Item Operation Sign Message',
      );
      values.fileName = values.files[0].originFileObj.name;
      values.fileType = values.files[0].originFileObj.type;
      values.fileSize = values.files[0].originFileObj.size;
      values.file = values.files[0].originFileObj;
      const response = await postItem({}, values);
      if (response?.success) {
        message.success('提交成功');
        const item = response.data!;
        formRef.current?.setFieldsValue({
          fileHash:item.fileHash,
          creator:item.creatorAddress,
        })
        return true;
      }
    } catch (e) {
      console.error(e);
      return false;
    }
    return false;
  }

  // 合约调用函数 todo tokenURL地址需要根据不同的环境进行动态修改
  const onFinish = async (values:FileStorageParams) => {
    try {
      const signer = provider.getSigner();

      const domain = {
        name: 'AQChain',
        version: '1',
        chainId: await signer.getChainId(),
        verifyingContract: fileStorageContract.address,
      };

      // The named list of all type definitions
      const types = {
        File: [
          { name: 'fileHash', type: 'string' },
          { name: 'creator', type: 'address' },
          { name: 'tokenURI', type: 'string' },
        ],
      };

      // The data to sign
      const value = {
        fileHash: values.fileHash,
        creator: values.creator,
        tokenURI: 'http://127.0.0.1:8000/api/item/'+values.fileHash,
      };

      const signature = await signer._signTypedData(domain, types, value);

      // console.log(await testContract.test(value.fileHash,value.creator,value.tokenURI,signature));

      const overrides = {
        gasPrice: await signer.getGasPrice(),
        gasLimit: 500000,
        nonce: await signer.getTransactionCount(),
      };

      // 预演执行合约
      console.log(await fileStorageContract.callStatic.create(
        value.fileHash,
        value.creator,
        value.tokenURI,
        signature,
        overrides,
      ));

      // 实际执行合约
      const tx = await fileStorageContract
        .connect(signer)
        .create(
          value.fileHash,
          value.creator,
          value.tokenURI,
          signature,
          overrides,
        );
      // 将合约交易记录执行更新
      await tx.wait();
      history.push('/item/itemTable');
    } catch (e) {
      console.error(e);
    }
  };

  return (
    <PageContainer>
      <ProCard>
        <StepsForm>
          <StepsForm.StepForm<API.FormDataModelsItemPost & {files:any}>
            name='upload'
            title='上传文件'
            onFinish={onFileUpload}
          >
            <ProFormText
              name='name'
              label='作品名称'
              width='md'
              rules={[{ required: true }]}
            />
            <ProFormTextArea
              name='description'
              label='作品介绍'
              width='lg'
              fieldProps={{ rows: 4 }}
            />
            <ProFormSelect
              name='category'
              label='作品类型'
              width='md'
              valueEnum={{
                1: '文字作品',
                2: '图片作品',
                3: '视频作品',
              }}
              rules={[{ required: true }]}
            />
            <ProFormUploadDragger
              name='files'
              label='作品上传'
              description='作品上传'
              rules={[{ required: true }]}
              max={1}
            />
          </StepsForm.StepForm>

          <StepsForm.StepForm<FileStorageParams>
            name='contract'
            title='数据上链'
            onFinish={onFinish}
            formRef={formRef}
          >
            <ProFormText
              label='文件Hash'
              name='fileHash'
              fieldProps={{ disabled: true }}
              rules={[{ required: true }]}
            />
            <ProFormText
              label='创建者'
              name="creator"
              fieldProps={{ disabled: true }}
              rules={[{ required: true }]}
            />
          </StepsForm.StepForm>
        </StepsForm>
      </ProCard>
    </PageContainer>
  );
};

export default AddItem;
